/*
 * Copyright (C) 2011-2015 ShenZhen iBOXPAY Information Technology Co.,Ltd.
 * 
 * All right reserved.
 * 
 * This software is the confidential and proprietary
 * information of iBoxPay Company of China. 
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement 
 * you entered into with iBoxpay inc.
 *
 */

package com.iboxpay.sdk;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The class ObjectUtil.
 *
 * Description: 
 *
 * @author: nieminjie
 * @since: 2016年2月29日	
 * @version: $Revision$ $Date$ $LastChangedBy$
 *
 */

public class ObjectUtil {

	/**
	 * 判断对象是否是基本数据类型
	 * @return
	 */
	public static boolean isBasicDataType(Class clazz) {
		boolean result = false;
		if (clazz.isPrimitive()) {
			result = true;
		} else if (String.class.equals(clazz)) {
			return result;
		} else {

			try {
				Field[] fields = clazz.getFields();
				if (null != fields) {
					for (Field field : fields) {
						if ("TYPE".equals(field.getName())) {
							result = ((Class) field.get(null)).isPrimitive();
							break;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 获取集合的元素类型
	 * @param collection
	 * @return
	 */
	public static List<Class<?>> getParameterClass(Class<?> genericClass) {
		List<Class<?>> clazz = Collections.emptyList();
		Type type = genericClass.getGenericSuperclass();
		if (null != type && type instanceof ParameterizedType) {
			ParameterizedType pt = (ParameterizedType) type;
			Type[] types = pt.getActualTypeArguments();
			if (null != types && types.length > 0) {
				clazz = new ArrayList<Class<?>>(types.length);
				for (Type temp : types) {
					clazz.add((Class<?>) temp);
				}
			}
		} else {
			Type[] interfaces = genericClass.getGenericInterfaces();
			if (null != interfaces && interfaces.length > 0) {
				for (Type interfaceType : interfaces) {
					if (interfaceType instanceof ParameterizedType) {
						ParameterizedType pt = (ParameterizedType) interfaceType;
						Type[] types = pt.getActualTypeArguments();
						if (null != types && types.length > 0) {
							clazz = new ArrayList<Class<?>>(types.length);
							for (Type temp : types) {
								clazz.add((Class<?>) temp);
							}
						}
					} else {
						clazz.addAll(getParameterClass((Class<?>) type));
					}
				}
			}
		}
		return clazz;
	}

}
